﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;
using Urb.Weather.Core;
using Urb.Weather.Core.Engine;
using Urb.Weather.Core.UI;
using Urb.Weather.Core.Provider;
using System.Windows;
using Urb.Weather.Core.Configuration;
using Urb.Weather.Core.Container;
using Urb.Weather.Core.Manager;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace Urb.Weather.Ticker
{
    internal class Bootstrapper
    {
        private IContainer container;

        internal void Configure()
        {
            var catalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            var mefContainer = new CompositionContainer(catalog);
                        
            this.container = mefContainer.GetExportedValue<IContainer>();
            var containerModule = mefContainer.GetExportedValue<IContainerModule>();
            containerModule.Configure(container);

            var engineModule = mefContainer.GetExportedValue<IEngineModule>();
            engineModule.Configure(container);

            var managerModule = mefContainer.GetExportedValue<IManagerModule>();
            managerModule.Configure(container);

            var uiModule = mefContainer.GetExportedValue<IUIModule>();
            uiModule.Configure(container);

            var weatherDataProviderModules = mefContainer.GetExportedValues<IWeatherDataProviderModule>();
            foreach (var weatherDataProviderModule in weatherDataProviderModules)
                weatherDataProviderModule.Configure(container);

            var configurationModule = mefContainer.GetExportedValue<IConfigurationModule>();
            configurationModule.Configure(container);
        }

        internal void Run(Application app)
        {
            Logger.Write("Started");

            IMainView mainView = container.Resolve<IMainView>();
            mainView.Model = container.Resolve<IMainViewModel>();

            mainView.Closed += new EventHandler(mainView_Closed);

            if (mainView is Window)
                app.MainWindow = mainView as Window;

            mainView.Show();
        }

        private void mainView_Closed(object sender, EventArgs e)
        {
            IManager manager = container.Resolve<IManager>();

            manager.Cleanup();
        }
    }
}
